import axios from "axios";
import vm from "@/main"; //引入vue实例
// export const port = "http://192.168.1.134:8844";
// export const port = "https://qjt9.qjnice.com";
export const port = "https://xcx.innjoysmart.me"; //端口地址

axios.defaults.baseURL = port;
axios.defaults.headers.common["Content-Type"] =
    "application/x-www-form-urlencoded";
// axios.defaults.headers.common["Authorization"] = localStorage.getItem("token");

axios.interceptors.request.use( //向服务端发送请求
    config => {
        // console.log(config);
        var TOKEN = localStorage.getItem("token");
        config.headers.Authorization = TOKEN;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

axios.interceptors.response.use( //获取服务端数据响应
    response => response,
    error => {
        var {
            response: {
                data,
                statusText,
                status
            }
        } = error;
        console.log(error.response);
        // var { code, message } = data;
        if (status === 401 && statusText === "Unauthorized") {
            vm.$router.replace({
                name: "Login"
            });
            // return false
        } else if (status === 400) {
            // if (code === "FAIL") {
            //     vm.$Message.error(message[0]);
            // } else {
            //     vm.$Message.error(data.ErrorMessage);
            // }
        } else {
            vm.$Message.error("系统出错！");
            // vm.$router.replace({ name: "Login" });
        }
        return Promise.reject(error);
    }
);

export function getQiniuToken() { //获取七牛token
    axios.get("/api/QiNiu/GetPublicToken").then(res => {
        console.log(res);
        var {
            data,
            code
        } = res.data;
        if (code == "SUCCESS") {
            localStorage.setItem("qiniu_token", data);
        } else {
            vm.$Message.error('获取七牛token失败,请刷新页面重试')
        }
    });
}

export function axiosDone( //请求成功后回调
    res,
    done,
    fail = () =>
    vm.$Message.error({
        content: msg,
        duration: 5,
        closable: true
    }),
    vm = this
) {
    console.log(res);
    var {
        code,
        data,
        msg
    } = res.data;
    if (code === "SUCCESS") {
        done && done();
    } else {
        fail && fail();
    }
}

export function axiosFail() {}
